///<reference path='../../typings/tsd.d.ts'/>

var crypto = require('crypto');
var ipfsAPI = require('ipfs-api');
import Config from "../config/Config";

/**
 * Ipfs存储类
 */
export default class Ipfs{
    
    protected static algorithm = 'aes-256-cbc';

    //加密
    public static cipher(key, data ,cb){
        var encrypted = "";
        var cip = crypto.createCipher(Ipfs.algorithm, key);
        encrypted += cip.update(data, 'binary', 'hex');
        encrypted += cip.final('hex');
        cb(encrypted);
    }

    //解密
    public static decipher(key,encrypted,cb){
        var decrypted = "";
        var decipher = crypto.createDecipher(Ipfs.algorithm, key);
        decrypted += decipher.update(encrypted, 'hex', 'binary');
        decrypted += decipher.final('binary');
        cb(decrypted);
    }

    //数据存储
    public static store(data:string,cb){
        var ipfs = ipfsAPI('localhost', '5001', {protocol: 'http'});
        // console.log(data);
        var content = Buffer.from(data);
        
        // const files = [
        //     {
        //         path: '/data0/uploadfile/',
        //         content: content
        //     }
        // ];
        
        ipfs.files.add(content, function (err, files) {
            console.log(files);
            cb(files);
        });
    }

    //获取hash对应内容
    public static get(hash:string,cb){
        var ipfs = ipfsAPI('localhost', '5001', {protocol: 'http'});
        console.log('ipfs cat hash:'+hash);

        ipfs.cat(hash, {buffer: true}, function (err, res) {
            if (err || !res) {
                return console.error('ipfs cat error', err, res)
            }
            // console.log('ipfs cat result:'+res.toString());
            cb(res.toString());
        })
    }
}